package com.example.mybatisplusdemo.web.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.service.IDeliveryAddressService;
import com.example.mybatisplusdemo.model.domain.DeliveryAddress;

import java.util.List;


/**
 *
 *  前端控制器
 *
 *
 * @author lqj
 * @since 2025-06-28
 * @version v1.0
 */
@RestController
@RequestMapping("/api/deliveryAddress")
public class DeliveryAddressController {

    private final Logger logger = LoggerFactory.getLogger( DeliveryAddressController.class );

    @Autowired
    private IDeliveryAddressService deliveryAddressService;


    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse<DeliveryAddress> getById(@PathVariable("id") Long id)throws Exception {
        DeliveryAddress deliveryAddress = deliveryAddressService.getById(id);
        return JsonResponse.success(deliveryAddress);
    }

    /**
     * 获取用户地址列表
     */
    @GetMapping("/user/{userId}")
    public JsonResponse<List<DeliveryAddress>> getByUserId(@PathVariable Long userId) {
        List<DeliveryAddress> list = deliveryAddressService.getByUserId(userId);
        return JsonResponse.success(list);
    }

    /**
     * 新增地址
     */
    @PostMapping
    public JsonResponse<Void> createAddress(@RequestBody DeliveryAddress address) {
        deliveryAddressService.save(address);
        return JsonResponse.success(null);
    }

    /**
     * 修改地址
     */
    @PutMapping("/{id}")
    public JsonResponse<Void> updateAddress(@PathVariable Long id, @RequestBody DeliveryAddress address) {
        address.setId(id);
        deliveryAddressService.updateById(address);
        return JsonResponse.success(null);
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/{id}")
    public JsonResponse<Void> deleteAddress(@PathVariable Long id) {
        deliveryAddressService.removeById(id);
        return JsonResponse.success(null);
    }

    /**
     * 设置默认地址
     */
    @PostMapping("/set-default")
    public JsonResponse<Void> setDefault(@RequestParam Long id, @RequestParam Long userId) {
        deliveryAddressService.setDefaultAddress(userId, id);
        return JsonResponse.success(null);
    }

    @GetMapping("/list/{userId}")
    public JsonResponse<List<DeliveryAddress>> getUserAddresses(@PathVariable Long userId) {
        List<DeliveryAddress> list = deliveryAddressService.getAddressesByUserId(userId);
        return JsonResponse.success(list);
    }

}

